package com.ch.ms.server.base.client;

import com.alibaba.fastjson.JSONObject;
import com.ch.ms.data.domain.account.ChmsAccount;
import com.ch.ms.server.packet.MaplePacket;
import io.netty.channel.Channel;
import lombok.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.UUID;


@Data
@Slf4j
@RequiredArgsConstructor
@ToString(exclude = "account")
public class MapleClientSession implements IoSession {
    @Setter(AccessLevel.NONE)
    private String id = UUID.randomUUID().toString();


    private ChmsAccount account;


    @NonNull
    private Channel channel;

    @Setter(AccessLevel.NONE)
    @Getter(AccessLevel.NONE)
    private JSONObject attributes = new JSONObject();


    @Override
    public void sendPacket(MaplePacket packet) throws SendPacketException {

        if (Objects.isNull(channel)) throw new SendPacketException("通道未建立");
        if (Objects.isNull(packet)) throw new SendPacketException("无效的数据包");

        channel.writeAndFlush(packet);

    }

    @Override
    public void close(SessionCloseReason reason) {
        if (Objects.isNull(this.channel)) return;
        if (channel.isOpen()) {
            log.info("close session [{}], reason is {}", channel, reason);
            channel.close();
        }
    }


    public void setAttribute(String key, Object value) {
        this.attributes.put(key, value);
    }


    public boolean getBooleanAttribute(String key, boolean defaultValue) {
        if (!this.attributes.containsKey(key)) return defaultValue;

        return this.attributes.getBoolean(key);
    }

}
